package com.sunny.ynhz.ui.index;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.google.gson.Gson;
import com.sunny.ynhz.R;
import com.sunny.ynhz.api.ApiService;
import com.sunny.ynhz.api.HttpManager;
import com.sunny.ynhz.api.upload.DefaultProgressListener;
import com.sunny.ynhz.api.upload.RetrofitUtil;
import com.sunny.ynhz.api.upload.UploadFileRequestBody;
import com.sunny.ynhz.app.GlobalVal;
import com.sunny.ynhz.bean.LocationBean;
import com.sunny.ynhz.bean.PathUploadBean;
import com.sunny.ynhz.bean.PatrolBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.model.RiverMsgModel;
import com.sunny.ynhz.ui.report.ChooseRiverActivityNative;
import com.sunny.ynhz.ui.base.BaseFragment;
import com.sunny.ynhz.ui.daily.indexproblem.HistoryActivity;
import com.sunny.ynhz.ui.patrol.PatrolRiverMoreStyleActivity;
import com.sunny.ynhz.ui.patrol.problems.OtherProblemReportActivity;
import com.sunny.ynhz.ui.patrol.problems.draft.DraftActivity;
import com.sunny.ynhz.utils.AlertUtils;
import com.sunny.ynhz.utils.FileUtils;
import com.sunny.ynhz.utils.SPUtil;
import com.sunny.ynhz.utils.ShowUtils;
import com.sunny.ynhz.utils.TimeFormatUtils;
import com.sunny.ynhz.utils.TimeIntervalUtils;
import com.sunny.ynhz.utils.ToastUtils;
import com.sunny.ynhz.utils.UUIDUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
import okhttp3.RequestBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 巡河fragment
 * Created by luao on 2017/7/19.
 */

public class NewPatrolFragment1 extends BaseFragment {

    @BindView(R.id.patrol_start)
    LinearLayout patrolStart;
    @BindView(R.id.patrol_problem_upload)
    LinearLayout patrolProblemUpload;
    @BindView(R.id.patrol_history)
    LinearLayout problemUploadWithoutPatrol;
    @BindView(R.id.draft)
    LinearLayout draft;
    @BindView(R.id.patrol_path_map)
    MapView patrolPathMap;
    @BindView(R.id.on_line)
    TextView reminder;
    @BindView(R.id.text_patrol)
    TextView textPatrol;
    @BindView(R.id.other_problem_upload)
    LinearLayout otherProblemUpload;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_distance)
    TextView tv_distance;
    @BindView(R.id.tv_last_start_time)
    TextView tv_last_start_time;
    @BindView(R.id.tv_gps)
    TextView tv_gps;


    private AMapLocationClient locationClient;
    private AMapLocationClientOption locationOption;
    private AMap aMap;
    boolean isFirstPositon = true;
    /**
     * 当前点到达的路径总长度
     */
    private File tempfile;
    private Marker startMarker;
    private Realm mRealm;
    private String riverId = "";
    private String riverName = "";
    private String userId;
    private PatrolBean patrolBean;
    private PolylineOptions polylineOptions;
    private String sectionId;
    /*
   * 当前时间和上次巡河时间相差分钟数
   */
    private long minite;
    private String time;
    private AlertUtils alertDiaoUtils;
    private RiverMsgModel riverMsgModel;
    private View view;
    private ListView lv_all_river;
    private BottomSheetDialog bottomSheetDialog;

    public static NewPatrolFragment1 getInstancePatrolFragment() {
        return new NewPatrolFragment1();
    }

    @Override
    protected int setLayoutResourceID() {
        return 0;
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int what = msg.what;
            if (what == 0) {//计算对应的时间
                if (patrolBean != null) {
                    tv_time.setVisibility(View.VISIBLE);
                    mRealm.executeTransaction(new Realm.Transaction() {
                        @Override
                        public void execute(Realm realm) {
                            patrolBean.setEndTime(TimeFormatUtils.getTime());
                        }
                    });

                    time = TimeIntervalUtils.getTime(patrolBean.getStartTime(), patrolBean.getEndTime());
                    tv_time.setText("巡河时长:" + time);
                    handler.sendEmptyMessageDelayed(0, 1000);
                    if (textPatrol.getText().toString().equals("开始巡河")) {
                        textPatrol.setText("结束巡河");

                    }
                } else {
                    handler.removeMessages(0);
                    textPatrol.setText("开始巡河");
                }
            }
            if (what == 1) {//计算距离
                if (patrolBean != null) {
                    tv_distance.setVisibility(View.VISIBLE);
                    tv_last_start_time.setVisibility(View.VISIBLE);
                    tv_last_start_time.setText("开始时间:" + patrolBean.getStartTime().replace(patrolBean.getLocationBeanlist().get(0).getTime().substring(0, 5), ""));
//                    String distance = CarUtils.getDistance(patrolBean.getLocationBeanlist());
//                    tv_distance.setText("巡河距离:" + distance);
                } else {
                    showPatrolDistanceTime();
                }
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mContentView = inflater.inflate(R.layout.fragment_patrol_path, null);
        ButterKnife.bind(this, mContentView);
        alertDiaoUtils = new AlertUtils();
        patrolPathMap.onCreate(savedInstanceState);// 此方法必须重写
        aMap = patrolPathMap.getMap();
        aMap.getUiSettings().setZoomControlsEnabled(false);
        positionInit();
        initLocation();
        startLocation();
        //如果定位不准就不让巡河
        tv_last_start_time.setVisibility(View.GONE);
        tv_distance.setVisibility(View.GONE);
        tv_time.setVisibility(View.GONE);
        textPatrol.setText("正在定位");
        minite = 30L;
        userId = SPUtil.get("userId", "null").toString();
        tempfile = FileUtils.createTmpJsonFile(activity);
        mRealm = RealmUtils.getDeleteRealm();
        RealmResults<PatrolBean> patrolBeanRealmList = mRealm.where(PatrolBean.class).equalTo("isEnd", false).equalTo("userId", userId).findAll();
        if (patrolBeanRealmList.size() != 0) {
            patrolBean = patrolBeanRealmList.get(0);
            mRealm.executeTransaction(realm -> patrolBean.setNeedContinue(true));
            Date dateLast = TimeFormatUtils.StrToDate(patrolBean.getLocationBeanlist().get(patrolBean.getLocationBeanlist().size() - 1).getTime());
            long timeBetween = (System.currentTimeMillis() - dateLast.getTime()) / 1000 / 60;
            if (timeBetween > minite) {
                dialogUploadPatrol();
            } else {
                dialogContinuePatrol();
            }
        } else {
            try {
                showPatrolDistanceTime();
            } catch (Exception e) {
            }
        }

        return mContentView;
    }

    private void showPatrolDistanceTime() {
        String distanceStr = SPUtil.get("lastDistance" + SPUtil.get("userId", ""), "暂无信息").toString();
        String timeStr = SPUtil.get("lastPatroltime" + SPUtil.get("userId", ""), "暂无信息").toString();
        String lastTime = SPUtil.get("lastStartTime" + SPUtil.get("userId", ""), "暂无信息").toString();
        if (!TextUtils.isEmpty(distanceStr)) {
            tv_distance.setVisibility(View.VISIBLE);
            tv_time.setVisibility(View.VISIBLE);
            tv_last_start_time.setVisibility(View.VISIBLE);
            tv_distance.setText("上次巡河距离:" + distanceStr);
            tv_time.setText("上次巡河时长:" + timeStr);
            tv_last_start_time.setText("上次开始时间:" + lastTime);
        }
    }

    /**
     * 是否开始巡河dialog
     */
    private void dialogConfirmStartPatrol() {
        String msg = "";
        if (riverName.equals("")) {
            msg = "是否开始巡河";
        } else {
            msg = "当前选择的河道是：\n" + riverName;
        }
        alertDiaoUtils.setMsg(msg);
        alertDiaoUtils.setTitle("提示");
        alertDiaoUtils.setEnsureButton("  是  ");
        alertDiaoUtils.setNegativeButton("  否  ");
        alertDiaoUtils.displayDiago(getActivity(), new AlertUtils.IClickButton() {
            @Override
            public void ensure() {
                startPatrol();
                alertDiaoUtils.closeDialog();
            }

            @Override
            public void cancel() {
                //不操作
                mRealm.executeTransaction(realm -> {
                    patrolBean.deleteFromRealm();
                    patrolBean = null;
                });
                alertDiaoUtils.closeDialog();
                sendMsgToChangeView();
            }
        });
    }

    /**
     * 是否提交巡河记录dialog
     */
    private void dialogUploadPatrol() {
        alertDiaoUtils.setEnsureButton("  是  ");
        alertDiaoUtils.setNegativeButton("  否  ");
        alertDiaoUtils.setTitle("系统自动结束巡河提示");
        alertDiaoUtils.setMsg("上次您的APP在巡河时非人为正常关闭，本次距上次已经超过" + minite + "分钟，系统将自动终止上次巡河，是否上传上次巡河记录");
        alertDiaoUtils.displayDiago(activity, new AlertUtils.IClickButton() {
            @Override
            public void ensure() {
                stopPatrol(true);
                alertDiaoUtils.closeDialog();
            }

            @Override
            public void cancel() {
                stopPatrol(false);
                alertDiaoUtils.closeDialog();
            }
        });
    }

    private void sendMsgToChangeView() {
        handler.sendEmptyMessage(0);
        handler.sendEmptyMessage(1);
    }

    /**
     * 是否继续巡河dialog
     */
    private void dialogContinuePatrol() {
        if ((Boolean) SPUtil.get("isAppExit", false)) {
            startPatrol();
            SPUtil.put("isAppExit", false);
        } else {
            alertDiaoUtils.setEnsureButton("  是 ");
            alertDiaoUtils.setNegativeButton("  否 ");
            alertDiaoUtils.setTitle("提示");
            alertDiaoUtils.setMsg("是否继续巡河");
            alertDiaoUtils.displayDiago(activity, new AlertUtils.IClickButton() {
                @Override
                public void ensure() {
                    startPatrol();
                    alertDiaoUtils.closeDialog();
                }

                @Override
                public void cancel() {
                    stopPatrol(false);
                    alertDiaoUtils.closeDialog();

                }
            });
        }
    }

    /**
     * 定位初始化
     */
    private void positionInit() {
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17.0f));
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_SHOW);//定位一次，且将视角移动到地图中心点。
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。\
    }


    @OnClick({R.id.patrol_start, R.id.patrol_problem_upload, R.id.patrol_history, R.id.draft, R.id.other_problem_upload, R.id.patrol_river_more_style})
    public void onClick(View view) {
        if (view.getId() == R.id.patrol_start) {
            if (textPatrol.getText().toString().equals("开始巡河")) {
                int userType = -1;
                try {
                    userType = Integer.parseInt(SPUtil.get("userType", "").toString());
                } catch (Throwable throwable) {
                    ToastUtils.SingleToastUtil(activity, "未能获取用户等级");
                }
                if (!(userType == 6 || userType == 11 || userType == 15)) {
                    Intent intent = new Intent(activity, ChooseRiverActivityNative.class);
                    startActivityForResult(intent, 600);
                } else {
                    getRiverStart();
                    dialogConfirmStartPatrol();
                }
            } else if (textPatrol.getText().toString().equals("结束巡河")) {
                Date dateLast = TimeFormatUtils.StrToDate(patrolBean.getLocationBeanlist().get(0).getTime());
                long timeBetween = (System.currentTimeMillis() - dateLast.getTime()) / 1000 / 60;
                final AlertUtils alertUtils = new AlertUtils();
                alertDiaoUtils.setEnsureButton(" 是 ");
                alertDiaoUtils.setNegativeButton(" 否 ");
                alertUtils.setTitle("提示");
                if (timeBetween < 30) {
                    alertUtils.setMsg("您当前巡河时长未达到30分钟,为无效巡河,是否结束?");
                } else {
                    alertUtils.setMsg("是否结束巡河?");
                }
                alertUtils.displayDiago(activity, new AlertUtils.IClickButton() {
                    @Override
                    public void ensure() {
                        stopPatrol(true);
                        alertUtils.closeDialog();
                    }

                    @Override
                    public void cancel() {
                        alertUtils.closeDialog();

                    }
                });
            }

        } else if (view.getId() == R.id.patrol_history) {
            doActivity(HistoryActivity.class);
        } else if (view.getId() == R.id.draft) {
            doActivity(DraftActivity.class);
        } else if (view.getId() == R.id.other_problem_upload) {
            Intent intent = new Intent(activity, OtherProblemReportActivity.class);
            intent.putExtra("isPatroling", isPatrolling);
            if (patrolBean != null) {
                intent.putExtra("patrolId", patrolBean.getId());
            }
            startActivity(intent);
        } else if (view.getId() == R.id.patrol_river_more_style) {
            doActivity(PatrolRiverMoreStyleActivity.class);

        }
    }

    private void getRiverStart() {
        riverName = "";
        AMapLocation location = GlobalVal.getaMapLocation();
        final LocationBean locationBean = new LocationBean();
        locationBean.setLttd(location.getLatitude());
        locationBean.setLgtd(location.getLongitude());
        locationBean.setTime(TimeFormatUtils.getTime());
        if (patrolBean == null) {
            mRealm.executeTransaction(realm -> {
                patrolBean = realm.createObject(PatrolBean.class, UUIDUtils.getRandomUUID());
                patrolBean.setEnd(false);
                patrolBean.setOnline(true);
                patrolBean.setUploaded(false);
                patrolBean.setStartTime(TimeFormatUtils.getTime());
                patrolBean.setUserId(userId);
                //添加第一个点
                patrolBean.getLocationBeanlist().add(realm.copyToRealm(locationBean));
                patrolBean.setStartLttd(locationBean.getLttd());
                patrolBean.setStartLgtd(locationBean.getLgtd());
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 600) {
            getRiverStart();
            riverName = data.getStringExtra("name");
            riverId = data.getStringExtra("reachId");
            sectionId = data.getStringExtra("id");
            mRealm.executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    patrolBean.setRiverId(riverId);
                    patrolBean.setSectionId(sectionId);
                }
            });
            dialogConfirmStartPatrol();
        }
    }

    public void uploadPatrolWithoutFile(String patrolId, String userId, final boolean isOnLine, String starttime, String endtime, String riverId, String sectionId, Float distance, final boolean isEnd, Double startLgtd, Double startLttd, Double endLgtd, Double endLttd) {
        HttpManager.getInstance().uploadPatrol(patrolId, userId, isOnLine, starttime, endtime, riverId, sectionId, distance, isEnd, startLgtd, startLttd, endLgtd, endLttd).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<PathUploadBean>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        ShowUtils.inItPopwin(activity, "正在同步服务器信息");
                    }

                    @Override
                    public void onCompleted() {
                        ShowUtils.closePopwindow();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ShowUtils.closePopwindow();
                        Toast.makeText(activity, "与服务器同步失败，正在用离线模式巡河", Toast.LENGTH_LONG).show();
                        mRealm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                patrolBean.setOnline(false);
                            }
                        });
                    }

                    @Override
                    public void onNext(PathUploadBean s) {

                    }
                });
    }

    public void uploadPatrol(String patrolId, String userId, boolean isOnLine, String starttime, String endtime, String riverId, String sectionId, Float distance, boolean isEnd, Double startLgtd, Double startLttd, Double endLgtd, Double endLttd, File file) {
        ApiService uploadFileService = RetrofitUtil.createService(ApiService.class);
        Map<String, RequestBody> requestBodyMap = new HashMap<>();
        UploadFileRequestBody fileRequestBody = new UploadFileRequestBody(file, new DefaultProgressListener(new Handler(), 1));
        requestBodyMap.put("jsonfile\"; filename=\"" + file.getName(), fileRequestBody);
        uploadFileService.uploadPatrol(patrolId, userId, isOnLine, starttime, endtime, riverId, sectionId, distance, isEnd, startLgtd, startLttd, endLgtd, endLttd, requestBodyMap).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Subscriber<PathUploadBean>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        ShowUtils.inItPopwin(activity, "正在上传巡河信息");
                    }

                    @Override
                    public void onCompleted() {
                        ShowUtils.closePopwindow();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ShowUtils.closePopwindow();
                        alertDiaoUtils.setTitle("提示");
                        alertDiaoUtils.setMsg("轨迹上传失败，已存入草稿箱\n请确认网络状况良好后手动上传");
                        alertDiaoUtils.setNegativeButton("我知道了");
                        alertDiaoUtils.setEnsureButton("");
                        alertDiaoUtils.displayDiago(activity, new AlertUtils.IClickButton() {
                            @Override
                            public void ensure() {
                                alertDiaoUtils.closeDialog();
                            }

                            @Override
                            public void cancel() {
                                alertDiaoUtils.closeDialog();
                            }
                        });
                        savaPatrolMsg();
                        patrolBean = null;
                        sendMsgToChangeView();
                    }

                    @Override
                    public void onNext(PathUploadBean s) {
                        ToastUtils.SingleToastUtil(activity, "轨迹上传成功");

                        mRealm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                patrolBean.setUploaded(true);
                            }
                        });

                        savaPatrolMsg();
                        patrolBean = null;
                        sendMsgToChangeView();
                    }


                });
    }

    private void savaPatrolMsg() {
        if (patrolBean != null) {
            RealmList<LocationBean> locationBeanlist = patrolBean.getLocationBeanlist();
            if (locationBeanlist != null && locationBeanlist.size() >= 1) {
//                LocationBean startLocationBean = locationBeanlist.get(0);
//                LocationBean endLocationBean1 = locationBeanlist.get(locationBeanlist.size() - 1);
                SPUtil.put("lastPatroltime" + SPUtil.get("userId", "").toString(), TimeIntervalUtils.getTime(patrolBean.getStartTime(), patrolBean.getEndTime()));
//                SPUtil.put("lastDistance" + SPUtil.get("userId", "").toString(), CarUtils.getDistance(patrolBean.getLocationBeanlist()));
                SPUtil.put("lastStartTime" + SPUtil.get("userId", "").toString(), patrolBean.getStartTime().replace(patrolBean.getStartTime().substring(0, 5), ""));
            }
        }

    }

    /**
     * 停止巡河
     */
    public void stopPatrol(boolean uploadPath) {
        reminder.setText("定位成功");
        isPatrolling = false;
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                int count = patrolBean.getLocationBeanlist().size();
                float distance = 0.0f;//路线距离
                LatLng latLng1;//第一个点
                LatLng latLng2;//第二个点
                for (int i = 1; i < count; i++) {
                    latLng1 = new LatLng(patrolBean.getLocationBeanlist().get(i - 1).getLttd(), patrolBean.getLocationBeanlist().get(i - 1).getLgtd());
                    latLng2 = new LatLng(patrolBean.getLocationBeanlist().get(i).getLttd(), patrolBean.getLocationBeanlist().get(i).getLgtd());
                    float distanceTemp = AMapUtils.calculateLineDistance(latLng1, latLng2);
                    distance = distance + distanceTemp;
                }
                patrolBean.setDistance(distance);
                patrolBean.setEndTime(TimeFormatUtils.getTime());
                patrolBean.setEnd(true);
                patrolBean.setUserId(userId);
                patrolBean.setNeedContinue(false);
                patrolBean.setEndLttd(patrolBean.getLocationBeanlist().get(count - 1).getLttd());
                patrolBean.setEndLgtd(patrolBean.getLocationBeanlist().get(count - 1).getLgtd());
            }
        });

        if (uploadPath) {
            Gson gson = new Gson();
            File jsonFile = FileUtils.getFileFromBytes(gson.toJson(mRealm.copyFromRealm(patrolBean.getLocationBeanlist())), tempfile.getPath());
            uploadPatrol(patrolBean.getId(), userId, patrolBean.isOnline(), patrolBean.getStartTime(), patrolBean.getEndTime(), patrolBean.getRiverId(), patrolBean.getSectionId(), patrolBean.getDistance() / 1000, true, patrolBean.getStartLgtd(), patrolBean.getStartLttd(), patrolBean.getEndLgtd(), patrolBean.getEndLttd(), jsonFile);
        } else {
            patrolBean = null;
            showPatrolDistanceTime();
            sendMsgToChangeView();
        }

        textPatrol.setText("开始巡河");
        if (polyline != null) {
            List<LatLng> list = polyline.getOptions().getPoints();
            endMarker = aMap.addMarker(
                    new MarkerOptions()
                            .position(list.get(list.size() - 1))
                            .title("终点").snippet("终点")
                            .draggable(false)
                            .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.end_marker)))
                            .setFlat(true));
        }
    }

    /**
     * 开始巡河
     */
    private void startPatrol() {
        isPatrolling = true;
        reminder.setText("正在巡河");
        textPatrol.setText("结束巡河");
        riverId = "";
        tv_last_start_time.setText("开始巡河时间为:" + TimeFormatUtils.getTime());
        //清楚上一次巡河的地图标绘
        if (polyline != null) {
            polyline.remove();
        }
        if (startMarker != null) {
            startMarker.remove();
        }
        if (endMarker != null) {
            endMarker.remove();
        }
        List<LatLng> latLngs = new ArrayList<>();
        int count = patrolBean.getLocationBeanlist().size();
        for (int i = 0; i < count; i++) {
            LatLng latLng1 = new LatLng(patrolBean.getLocationBeanlist().get(i).getLttd(), patrolBean.getLocationBeanlist().get(i).getLgtd());
            latLngs.add(latLng1);
        }
        startMarker = aMap.addMarker(
                new MarkerOptions()
                        .position(latLngs.get(0))
                        .title("起点").snippet("起点")
                        .draggable(false)
                        .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.begin_marker)))
                        .setFlat(true));
        polylineOptions = new PolylineOptions().width(10).color(Color.RED);//在这里初始化，每次开始都要有新的轨迹点记录，否则会和之前的轨迹点连起来
        polylineOptions.addAll(latLngs);
        polyline = aMap.addPolyline(polylineOptions);
        //开始巡河的请求, 继续巡河不需要请求
        if (!patrolBean.isNeedContinue()) {
            uploadPatrolWithoutFile(patrolBean.getId(), userId, patrolBean.isOnline(), patrolBean.getStartTime(), patrolBean.getEndTime(), patrolBean.getRiverId(), patrolBean.getSectionId(), null, false, patrolBean.getStartLgtd(), patrolBean.getStartLttd(), patrolBean.getEndLgtd(), patrolBean.getEndLttd());
        }
        sendMsgToChangeView();
    }

    private boolean isPatrolling = false;
    private Marker endMarker;
    private Polyline polyline;
    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {

        private LocationBean locationBean = new LocationBean();

        @Override
        public void onLocationChanged(final AMapLocation location) {
            if (null != location) {
                if (location.getErrorCode() == 0) {
                    GlobalVal.setaMapLocation(location);
                    int gpsAccuracyStatus = location.getGpsAccuracyStatus();
                    switch (gpsAccuracyStatus) {
                        case AMapLocation.GPS_ACCURACY_GOOD://卫星信号强
                            tv_gps.setText("GPS信号强");
                            break;
                        default://卫星信号弱
                            tv_gps.setText("GPS信号较弱");
                            break;
                    }

                    if (isFirstPositon) {
                        textPatrol.setText("开始巡河");
                        reminder.setText("定位成功");
//                        MarkOptionUtils.setCenterPosition(aMap, new LatLng(location.getLatitude(), location.getLongitude()));
                        isFirstPositon = false;
                    }
                    if (!isPatrolling && location.getAccuracy() < 100) {
                        reminder.setText("定位成功");
                        int satellites = location.getSatellites();

                    }
                    if (isPatrolling && location.getAccuracy() < 100) {
                        locationBean.setLttd(location.getLatitude());
                        locationBean.setLgtd(location.getLongitude());
                        locationBean.setTime(TimeFormatUtils.getTime());
                        mRealm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                patrolBean.getLocationBeanlist().add(realm.copyToRealm(locationBean));
                            }
                        });
                        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
                        polylineOptions.add(latLng);
                        polyline.setOptions(polylineOptions);
                        handler.sendEmptyMessage(1);
                    }
                } else {
                    if (!isPatrolling) {
                        reminder.setText("定位失败");
                    }
                }
            } else {
                reminder.setText("定位初始化失败，请关闭手机后重试，或联系手机厂商。。");
            }
        }
    };


    /**
     * 定位初始化
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(activity);
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(true);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(10000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(3000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 开始定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void startLocation() {
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    public boolean isPatrolling() {
        return isPatrolling;
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            stopLocation();
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        destroyLocation();
        handler.removeMessages(0);
        handler.removeMessages(1);
    }


}